package com.adcc.ags.gms.core.service;

import com.adcc.ags.gms.core.entity.GWLogLevel;
import com.adcc.ags.gms.core.mapper.MenuMapper;
import com.adcc.ags.gms.core.entity.Menu;
import com.adcc.ags.gms.core.util.LogFactory;
import com.adcc.ags.gms.core.vo.MenuVO;
import com.adcc.ags.gms.core.vo.SubMenuVO;
import com.google.common.base.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 核心服务实现类
 */
@Transactional
@Service("CoreService")
public class CoreServiceImpl implements CoreService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private LogFactory log;

    @Override
    public Optional<List<MenuVO>> findMenuItemByUserType(int type) {
        try{
            List<MenuVO> menuVOList = new ArrayList<MenuVO>();
            List<SubMenuVO> subMenuVOlist = new ArrayList<SubMenuVO>();
            List<Menu> list = menuMapper.findMenuItemByUserType(type);
            //一级节点
            for (Menu menu : list) {
                if (menu.getParentId() == 0) {
                    MenuVO menuVO = new MenuVO();

                    menuVO.setId(menu.getId());
                    menuVO.setName(menu.getName());
                    menuVO.setTextCN(menu.getTextCN());
                    menuVO.setTextEN(menu.getTextEN());
                    menuVO.setUrl(menu.getUrl());
                    menuVO.setRemark(menu.getRemark());
                    menuVO.setSubMenuVOList(subMenuVOlist);

                    menuVOList.add(menuVO);
                }
            }
            for(int i = 0;i < menuVOList.size();i++){
                subMenuVOlist = new ArrayList<SubMenuVO>();
                for (Menu menu : list) {
                    if (menuVOList.get(i).getId() == menu.getParentId()) {
                        SubMenuVO subMenuVO = new SubMenuVO();

                        subMenuVO.setId(menu.getId());
                        subMenuVO.setName(menu.getName());
                        subMenuVO.setTextCN(menu.getTextCN());
                        subMenuVO.setTextEN(menu.getTextEN());
                        subMenuVO.setUrl(menu.getUrl());
                        subMenuVO.setRemark(menu.getRemark());

                        subMenuVOlist.add(subMenuVO);
                    }
                }
                menuVOList.get(i).setSubMenuVOList(subMenuVOlist);
            }
            return Optional.of(menuVOList);
        } catch (Exception ex) {
            log.error(CoreService.class, "Menu", GWLogLevel.ALARM, "查询菜单失败", ex);
            return Optional.absent();
        }
    }
}
